<style>
#wxLoginForm {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 2px solid black;
  background-color: white; /* 添加浅蓝色背景 */
  padding: 20px; /* 可以根据需要调整内边距 */
  display: none; /* 如果需要隐藏，可以在其他地方根据条件进行显示 */
}

body {
  margin: 0;
  padding: 0;
}

.center {
  width: 1920px;
  height: 1080px;
  background-image: url('https://cdn.pixabay.com/photo/2016/07/09/07/48/blue-sky-1505848_1280.jpg');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

h1 {
  font-size: 30px;
  color: black;
}

.logon {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
  /* position: relative;
  overflow: hidden; */
  width: 768px;
  max-width: 100%;
  min-height: 480px;
  margin-top: 20px;
  display: flex;
  background: -webkit-linear-gradient(right, #4284db, #29eac4);
}

.overlaylong {
  border-radius: 10px 0 0 10px;
  width: 50%;
  height: 100%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.overlaylongleft {
  border-radius: 0px 10px 10px 0px;
  width: 50%;
  height: 100%;
  background-color: #fff;
  transform: translateX(100%);
  transition: transform 0.6s ease-in-out;
  display: flex;
  align-items: center;
  justify-content: center;
}

.overlaylongright {
  border-radius: 10px 0 0 10px;
  width: 50%;
  height: 100%;
  background-color: #fff;
  transform: translateX(0%);
  transition: transform 0.6s ease-in-out;
  display: flex;
  align-items: center;
  justify-content: center;
}

.overlaytitle {
  border-radius: 0px 10px 10px 0px;
  width: 50%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);
  display: flex;
  align-items: center;
  justify-content: center;
}


.overlaytitleH2 {
  font-size: 30px;
  color: #fff;
  margin-top: 20px;
}

.overlaytitleP {
  font-size: 15px;
  color: #fff;
  margin-top: 20px;
}

.overlaytitleleft {
  border-radius: 0px 10px 10px 0px;
  width: 50%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);
  display: flex;
  align-items: center;
  justify-content: center;
  transform: translateX(0%);
  transition: transform 0.6s ease-in-out;
}

.overlaytitleright {
  border-radius: 0px 10px 10px 0px;
  width: 50%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);
  display: flex;
  align-items: center;
  justify-content: center;
  transform: translateX(-100%);
  transition: transform 0.6s ease-in-out;
}

.overlaytitle-Signin {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.overlaytitle-Signup {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.buttongohs {
  width: 180px;
  height: 40px;
  border-radius: 50px;
  border: 1px solid #fff;
  color: #fff;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
  margin-top: 40px;
}

.overlaylongH2 {
  font-size: 25px;
  color: black;
  /* width: 250px; */
}

.overlaylong-Signin {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.overlaylong-Signup {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

input {
  background-color: #eee;
  border: none;
  padding: 12px 15px;
  margin: 10px 0;
  width: 240px;
  border-radius: 10px;
}

h3 {
  font-size: 10px;
  margin-top: 10px;
  cursor: pointer;
}

.inupbutton {
  background-color: #29eac4;
  border: none;
  width: 180px;
  height: 40px;
  border-radius: 50px;
  font-size: 15px;
  color: #fff;
  text-align: center;
  line-height: 40px;
  margin-top: 10px;
}

h3 {
  display: flex;
  justify-content: space-between; /* 让两个<a>元素分别对齐左右 */
}

input[type="radio"] {
  padding: 0;
  margin: 0;
}

.error-message {
  color: red;
  font-size: 15px;
}

.box {
  width: 400px;

  .top {
    text-align: center;
  }

  .left {
    float: left;
    width: 60px;
  }

  .right {
    float: right;
    width: 60px;
  }

  .bottom {
    clear: both;
    text-align: center;
  }

  .item {
    margin: 4px;
  }

  .left .el-tooltip__popper,
  .right .el-tooltip__popper {
    padding: 8px 10px;
  }
}
</style>

<template>
  <div class="center">
    <!--    <h1>登录 / 注册</h1>-->
    <div class="logon">
      <div :class="overlaylong">
        <div class="overlaylong-Signin" v-if="disfiex == 0">
          <h2 class="overlaylongH2">登录</h2>
          <el-tooltip class="item" effect="light" :content="phoneError" placement="right"
                      :style="{border: phoneError==='康' ? '' : '1px solid #f47b7b'}">
            <input type="text" placeholder="电话号码" v-model="userData.username" v-phone-validator>
          </el-tooltip>
          <el-tooltip class="item" effect="light" :content="passwordError" placement="right"
                      :style="{border: passwordError==='同' ? '' : '1px solid #f47b7b'}">
            <input type="password" placeholder="密码" v-model="userData.password" v-password-validator>
          </el-tooltip>
          <div style="display: flex;flex-direction: row">
            <input type="text" v-model="userData.code" placeholder="验证码"
                   style="width: 150px;float: left;display: block; float: left;margin-left: 30px">
            <span style="display: block; float: left;margin: 15px 0 0 20px">
              <img :src="verifyImgUrl" alt="验证码" id="verifyimg" @click="getvCode">
              <!-- 验证码 显示 -->
              <img οnclick="javascript:getvCode()" id="verifyimg" style="margin-left: 20px;"/>
            </span>
          </div>
          <h3>
            <a href="" style="text-decoration: none;margin: 0 74px 0 54px">忘记密码？</a>
            <span style="position: relative;margin: 0 66px;">
              <label style="margin: auto">七天免登录</label>
              <input type="checkbox" v-model="checked"
                     style="width: 16px;position:absolute;margin-left: 2px;margin-top: 1px">
            </span>
          </h3>
          <button class="inupbutton" @click="login">登录</button>
          <div style="margin-top: 30px;">
            <img src="http://medical-registration-imgs.oss-cn-wuhan-lr.aliyuncs.com/images/QQ.png" alt="QQ账号登录"
                 style="height: 30px;margin-right: 50px">
            <img src="http://medical-registration-imgs.oss-cn-wuhan-lr.aliyuncs.com/images/weixin.png"
                 alt="微信账号登录" @click="weiXinLogin" style="height: 30px;margin-right: 50px">
            <img
                src="http://medical-registration-imgs.oss-cn-wuhan-lr.aliyuncs.com/images/%E6%94%AF%E4%BB%98%E5%AE%9D%E6%94%AF%E4%BB%98%402x.png"
                alt="支付宝账号登录" style="height: 30px">
          </div>
        </div>
        <div class="overlaylong-Signup" v-if="disfiex == 1">
          <h2 class="overlaylongH2">注册账号</h2>
          <el-tooltip class="item" effect="light" :content="nameError" placement="right"
                      :style="{border: nameError==='与' ? '' : '1px solid #f47b7b'}">
            <input type="text" placeholder="姓名" v-model="userData.username" v-name-validator>
          </el-tooltip>
          <el-tooltip class="item" effect="light" :content="nicknameError" placement="right"
                      :style="{border: nicknameError==='健' ? '' : '1px solid #f47b7b'}">
            <input type="text" placeholder="昵称" v-model="userData.nickname" v-nickname-validator>
          </el-tooltip>
          <el-tooltip class="item" effect="light" :content="phoneError" placement="right"
                      :style="{border: phoneError==='康' ? '' : '1px solid #f47b7b'}">
            <input type="text" placeholder="电话号码" v-model="userData.phone" v-phone-validator>
          </el-tooltip>
          <el-tooltip class="item" effect="light" :content="passwordError" placement="right"
                      :style="{border: passwordError==='同' ? '' : '1px solid #f47b7b'}">
            <input type="password" placeholder="密码" v-model="userData.password" v-password-validator>
          </el-tooltip>
          <el-tooltip class="item" effect="light" :content="testError" placement="right">
            <input type="password" placeholder="确认密码" v-model="confirmPassword"
                   :style="{border: isPasswordMatch ? '' : '1px solid #f47b7b'}">
          </el-tooltip>
          <button class="inupbutton" @click="register()">完成注册</button><!--:disabled="!isPasswordMatch"-->
        </div>

      </div>
      <div :class="overlaytitle">
        <div class="overlaytitle-Signin" v-if="disfiex == 0">
          <h2 class="overlaytitleH2">没有账号？</h2>
          <p class="overlaytitleP">
            点击此处，输入你的信息即可完成注册
          </p>
          <div class="buttongohs" @click="Signin">注册</div>

        </div>
        <div class="overlaytitle-Signup" v-if="disfiex == 1">
          <h2 class="overlaytitleH2">已有账号!</h2>
          <p class="overlaytitleP">要与我们保持联系请用个人信息登录</p>
          <div class="buttongohs" @click="Signup">登录</div>
        </div>
      </div>
    </div>

    <!-- 二维码 -->
    <div id="wxLoginForm" style="display: none">
      <h2>微信登录</h2>
      <!--<img src="images/wxlogin.png">-->
    </div>
  </div>


</template>
<!--http://medical-registration-imgs.oss-cn-wuhan-lr.aliyuncs.com/images/QQ.png————qq图标-->
<!--http://medical-registration-imgs.oss-cn-wuhan-lr.aliyuncs.com/images/weixin.png————微信-->
<!--http://medical-registration-imgs.oss-cn-wuhan-lr.aliyuncs.com/images/%E6%94%AF%E4%BB%98%E5%AE%9D%E6%94%AF%E4%BB%98%402x.png————支付宝（原版）-->
<!--http://medical-registration-imgs.oss-cn-wuhan-lr.aliyuncs.com/images/%E6%94%AF%E4%BB%98%E5%AE%9D%E6%94%AF%E4%BB%98.png————支付宝（垃圾版）-->
<script>
import axios from "axios";

export default {
  data() {
    return {
      /*登录页面参数*/
      overlaylong: 'overlaylong',
      overlaytitle: 'overlaytitle',
      disfiex: 0,
      /*注册的数据*/
      userData: {
        username: "",
        nickname: "",   // 昵称
        password: "",
        phone: "",
        code: ""   // 验证码
      },
      confirmPassword: "", // 验证密码
      /*验证码参数*/
      verifyImgUrl: "",
      /*message*/
      nameError: '与',
      nicknameError: '健',
      phoneError: '康',
      passwordError: '同',
      testError: '行',
      /*验证的参数*/
      checked: false,
    }
  },
  computed: {
    isPasswordMatch() {   /*false===red*/
      let pass = this.userData.password;
      let conPass = this.confirmPassword;
      if (pass !== '' && pass !== null) {
        if (conPass !== '' && conPass !== null) {
          return pass === conPass;
        }
      } else {
        if (conPass !== '' && conPass !== null) {
          return false;
        } else {
          return true;
        }
      }
      return true;
    }
  },
  mounted() {   // 钩子函数
    this.getvCode();
    /*七天免登录*/
    //判断复选框是否被勾选 勾选则调用配置cookie方法
    if (this.checked == true) {
      //传入账号名，密码，和保存天数3个参数
      this.setCookie(this.userData.phone, this.userData.password, 7);
    } else {
      console.log("清空Cookie");
      //清空Cookie
      this.clearCookie();
    }
  },
  created() {
    //初始化微信js
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
    document.body.appendChild(script)
  },
  methods: {
    /*微信登录*/
    weiXinLogin() {
      // 显示二维码的容器
      console.log("微信登录二维码显示")
      document.getElementById("wxLoginForm").style.display = "block";
      // 到后台获得微信登录参数
      axios.get("/api/ucenter/wx/getWxParam")
          .then(res => {
            console.log("wxparam", res)
            //创建微信登录对象，显示二维码 id 显示二维码容器的id
            var obj = new WxLogin({
              self_redirect: true,
              id: "wxLoginForm",
              appid: res.data.data.appid,
              scope: res.data.data.scope,
              redirect_uri: res.data.data.redirectUri,
              state: res.data.data.state,
              style: "black", //black white 二维码样式
              href: ""
            });
          });
      //定时器读取用户信息

      var count = 0;
      var timer = window.setInterval(()=>{
        //读取后台是否返回用户信息保存到前端
        let user = localStorage.getItem("user");
        this.user = JSON.parse(user)
        if(this.user){
          this.$message('登录成功')
          console.log("user",this.user.nickname)
          document.getElementById("wxLoginForm").style.display = "none";
          window.clearInterval(timer);
          this.$router.push('/index');
        }
        count++;
        if(count == 10){
          document.getElementById("wxLoginForm").style.display = "none";
          window.clearInterval(timer);
        }
      },3000);



    },
    /*登录提交*/
    login() {
      console.log(this.userData)
      //验证码 + 登录
      console.log("验证码验证", this.userData.code)
      axios.get("/code/verification", {params: {code: this.userData.code}})
          .then(res => {
            if ("OK" === res.data.status) {
              console.log(res.data)
              console.log("验证码验证成功")
              // 执行登录操作
              const user = {
                'username': this.userData.username,
                'password': this.userData.password,
              }
              console.log(user);
              axios.post("/login", this.$qs.stringify(user))
                  .then(res => {
                    console.log(res.data)
                    if ("OK" === res.data.status) {
                      console.log("登录成功")
                      console.log("token", res.data.accessToken)
                      this.userData = {
                        username: "",
                        nickname: "",   // 昵称
                        password: "",
                        phone: "",
                        code: ""   // 验证码
                      }
                      if (res.data.accessToken) {
                        //登录成功，保存token到localStorage
                        localStorage.setItem("access-token", res.data.accessToken);
                        this.user = res.data.data;
                        console.log("user", this.user)
                        localStorage.setItem("user", JSON.stringify(this.user));
                      }
                      /*跳转到首页*/
                      this.$router.push('/index');
                    } else {
                      console.log("登录失败")
                      this.open1('登录失败，账号或密码错误')
                    }
                  })
            } else {
              console.log("验证码验证失败")
              this.open1('登录有误，验证码验证失败')
            }
            this.getvCode()
          })

    },
    /*注册提交*/
    register() {
      /*验证是否能够注册*/
      if (this.nameError !== '与' || this.nicknameError !== "健" || this.phoneError !== "康" || this.passwordError !== "同" || !this.isPasswordMatch ||
          this.userData.username === '' || this.userData.password === '' || this.userData.nickname === '' || this.userData.phone === '' || this.confirmPassword === '') {
        console.log("无法注册,原因是你的输入有不合法存在")
        this.open1('无法注册,原因是你的输入有不合法存在')
        return;
      }
      /*注册业务*/
      console.log("注册")
      console.log("注册数据", this.userData)
      axios.post("/register", this.userData)
          .then(res => {
            console.log(res.data)
            if ("OK" === res.data.status) {
              /*将username的内容剪切到phone，并清除username*/
              this.userData.phone = this.userData.username;
              this.userData.username = '';
              console.log("注册成功")
              this.Signup();
            } else {
              console.log("注册失败")
            }
          })
      this.Signup();
    },
    Signin() {
      /*将username的内容剪切到phone，并清除username*/
      let name = this.userData.phone;
      this.userData.phone = this.userData.username;
      this.userData.username = name;
      this.overlaylong = "overlaylongleft"
      this.overlaytitle = "overlaytitleright"
      setTimeout(() => {
        this.disfiex = 1
      }, 200)
    },
    Signup() {
      /*将phone的内容剪切到username，并清除phone*/
      this.userData.username = this.userData.phone;
      this.userData.phone = '';
      this.overlaylong = "overlaylongright"
      this.overlaylong = "overlaylongright"
      this.overlaytitle = "overlaytitleleft"

      setTimeout(() => {
        this.disfiex = 0
      }, 200)

    },
    timestamp(url) {
      const getTimestamp = new Date().getTime();
      if (url.indexOf("?") > -1) {
        url = url + "&timestamp=" + getTimestamp;
      } else {
        url = url + "?timestamp=" + getTimestamp;
      }
      return url;
    },
    /*刷新验证码*/
    getvCode() {
      this.verifyImgUrl = this.timestamp("http://localhost:9000/code/verifyCode");
      console.log("当前验证码：" + this.verifyImgUrl)
    },
    open1(string) {
      this.$notify({
        title: '注意⚠️',
        message: string
      });
    },
    open2() {
      this.$notify({
        title: '错误 ❗️️',
        message: '无法注册,原因是你的输入有不合法存在'
      });
    },
    /*七天免登录*/
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie = "phone" + "=" + this.userData.phone + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie = "password" + "=" + this.userData.password + ";path=/;expires=" + exdate.toGMTString();
    },
    //读取cookie
    getCookie: function () {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split('='); //再次切割
          //判断查找相对应的值
          if (arr2[0] == 'phone') {
            //  console.log(arr2[1])
            this.userData.phone = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] == 'password') {
            // console.log(arr2[1])
            this.userData.password = arr2[1];
          }
        }
        this.checked = true;
      }
    },
    //清除cookie
    clearCookie: function () {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
    },
  },
  /*验证表单数据*/
  directives: {
    nameValidator: {
      bind(el, binding, vnode) {
        el.addEventListener('blur', () => {
          const name = el.value.trim();
          if (/\d/.test(name)) {
            vnode.context.nameError = '姓名不能包含数字';
          } else if (name.length < 1 || name.length > 16) {
            vnode.context.nameError = '姓名长度必须在1到16个字符之间';
          } else {
            vnode.context.nameError = '与';
          }
        });
      }
    },
    nicknameValidator: {
      bind(el, binding, vnode) {
        el.addEventListener('blur', () => {
          const nickname = el.value.trim();
          if (nickname.length < 1 || nickname.length > 16) {
            vnode.context.nicknameError = '昵称长度必须在1到16个字符之间';
          } else {
            vnode.context.nicknameError = '健';
          }
        });
      }
    },
    phoneValidator: {
      bind(el, binding, vnode) {
        el.addEventListener('blur', () => {
          const phoneNumber = el.value.trim();
          const phoneRegex = /^1[3456789]\d{9}$/;
          if (!phoneRegex.test(phoneNumber)) {
            vnode.context.phoneError = '请输入有效的电话号码';
          } else {
            vnode.context.phoneError = '康';
          }
        });
      }
    },
    passwordValidator: {
      bind(el, binding, vnode) {
        el.addEventListener('blur', () => {
          const password = el.value.trim();
          if (password.length < 6 || password.length > 33) {
            vnode.context.passwordError = '密码长度必须在6到33个字符之间';
          } else {
            vnode.context.passwordError = '同';
          }
        });
      },
    }
  }
}
</script>
